from collections import Counter
# from icecream import ic
import json
import pandas as pd
import requests


def gen_wafermap_config(info_dic, sql_info):
    dasHost = sql_info['dasHost']
    url = dasHost+'/dc/wafermap/config'
    if info_dic['test_stage'] == 'VIRTUAL_STAGE':
        test_stage = info_dic['real_test_stage']
    else:
        test_stage = info_dic['test_stage']
    request_data = {
        "configType": "ORIGINAL",
        "customer": info_dic['customer'],
        "dataSourceList": info_dic['dataSourceList'],
        "deviceId": info_dic['device_id'],
        "factoryList": info_dic['factoryList'],
        "factorySiteList": info_dic['factorySiteList'],
        "queryCkFlag": False,
        "subCustomer": "",
        "testArea": info_dic['test_area'],
        "testStageList": [test_stage]
    }
    headers = {'Content-Type': 'application/json'}
    response = requests.post(url, headers=headers, json=request_data)
    response = json.loads(response.text)
    return response


def gen_wafermap_config_mapping(info_dic, sql_info):
    dasHost = sql_info['dasHost']
    url = dasHost+'/dc/wafermap/config/mapping'
    if info_dic['test_stage']=='VIRTUAL_STAGE':
        test_stage=info_dic['real_test_stage']
    else:
        test_stage=info_dic['test_stage']
    request_data = {
        "configType": "ORIGINAL",
        "customer": info_dic['customer'],
        "dataSourceList": info_dic['dataSourceList'],
        "deviceId": info_dic['device_id'],
        "factoryList": info_dic['factoryList'],
        "factorySiteList": info_dic['factorySiteList'],
        "queryCkFlag": True,
        "subCustomer": "",
        "testArea": info_dic['test_area'],
        "testStageList": [test_stage]
    }
    headers = {'Content-Type': 'application/json'}
    response = requests.post(url, headers=headers, json=request_data)
    response = json.loads(response.text)
    # ic(response)
    res = pd.DataFrame(response['data'])
    res['originalDie'] = res.apply(lambda row: (
        row['originalDieX'], row['originalDieY']), axis=1)
    # res=pd.DataFrame(response['data'])
    # res = res.sort_values(by=['originalDieX', 'originalDieY'], ascending=[True, True])
    return res


if __name__ == '__main__':
    from get_sql_res import gen_run_detail
    from gen_info_dic import gen_info_dic
    rule_run_record_id = 7088
    wafer_id = 'NW2GM_04'
    df_run_detail = gen_run_detail(rule_run_record_id)
    info_dic = gen_info_dic(df_run_detail)
    ##
    res = gen_wafermap_config_mapping(info_dic)
    # ic(res)
    # res.to_csv('aaa.csv')
